/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.utils;

import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.exception.domain.MoonException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;

/**
 * 加解密
 * @author moon
 */
@Slf4j
public class SecurityUtils {

    /**AES密钥*/
    private final static String AES_KEY = "moon;OIU0987++==";
    /**AES密钥长度16位*/
    private final static int AES_KEY_LENGTH = 16;

    /**
     * md5 结果为小写
     */
    public static String md5(String data) {
        StringBuilder sign = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(data.getBytes("UTF-8"));
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(bytes[i] & 0xFF);
                if (hex.length() == 1) {
                    sign.append("0");
                }
                sign.append(hex.toLowerCase());
            }
        } catch (Exception gse) {
            log.error(gse.getMessage(),gse);
            throw new MoonException("md5 加密失败");
        }
        return sign.toString();
    }

    /**
     * AES 加密
     */
    public static String aesEncrypt(String sSrc){
        if (AES_KEY.length() != AES_KEY_LENGTH) {
            throw new MoonException("加密密钥必须是16位");
        }
        try {
            byte[] raw = AES_KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            //此处使用BASE64做转码功能，然后再用url编码，同时能起到2次加密的作用
            String str = new BASE64Encoder().encode(encrypted);
            return URLEncoder.encode(str,"utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new MoonException("AES 加密失败");
        }
    }

    /**
     * AES 解密
     */
    public static String aesDecrypt(String sSrc){
        if (AES_KEY.length() != AES_KEY_LENGTH) {
            throw new MoonException("加密密钥必须是16位");
        }
        try {
            byte[] raw = AES_KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            sSrc = URLDecoder.decode(sSrc,"UTF-8");
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,"utf-8");
            return originalString;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new MoonException("AES 解密失败");
        }
    }
}
